package com.rt.config.resource.exception;

import com.rt.easyjava.common.base.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component("customAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException)
            throws IOException, ServletException {
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = "权限不足";
        map.put("code", 403);//401
        map.put("msg", msg);
        map.put("data", accessDeniedException.getMessage());
        map.put("path", request.getServletPath());
        map.put("timestamp", String.valueOf(new Date().getTime()));

        try {
            Result.builder(map).fault(msg).response(response);
        } catch (Exception e) {
            throw new ServletException();
        }

    }
}
